package CPOO;

import java.awt.image.BufferedImage;

public class HistogramRate {

	private static int L = 255;

	private static int[][] convertToGrayScale(int[][][] img) {
		int[][] grayScaleImage = new int[img.length][img[0].length];
		double[] weightConvert = { 0.299, 0.587, 0.114 };
		int j=0;
		for (int i = 0; i < img.length; ++i) {
			for (j = 0; j < img[0].length; ++j) {
				// x = 0.299r + 0.587g + 0.114b.
				grayScaleImage[i][j] = (int) (weightConvert[0] * img[i][j][0]
						+ weightConvert[1] * img[i][j][1] + weightConvert[2]
						* img[i][j][2]);
			}
		}
		return grayScaleImage;
	}

	private static int getLMax(int[][] grayImg) {
		int lmax = grayImg[0][0];
		for (int i = 0; i < grayImg.length; ++i) {
			for (int j = 0; j < grayImg[0].length; ++j) {
				if (lmax < grayImg[i][j])
					lmax = grayImg[i][j];
			}
		}
		return lmax;
	}

	private static int getLMin(int[][] grayImg) {
		int lmin = grayImg[0][0];
		for (int i = 0; i < grayImg.length; ++i) {
			for (int j = 0; j < grayImg[0].length; ++j) {
				if (lmin > grayImg[i][j])
					lmin = grayImg[i][j];
			}
		}
		return lmin;
	}

	private static double getLmean(int[][] grayImg) {
		double lmean = 0;
		for (int i = 0; i < grayImg.length; ++i) {
			for (int j = 0; j < grayImg[0].length; ++j) {
				lmean += grayImg[i][j];
			}
		}
		lmean /= (grayImg.length * grayImg[0].length);
		return lmean;
	}

	public static double calcK1(int[][][] img) {
		int[][] gray = new int[img.length][img[0].length];
		gray = convertToGrayScale(img);
		return (getLMax(gray) - getLMin(gray)) / (double) L;
	}

	public static double calcK2(int[][][] img) {
		int[][] gray = new int[img.length][img[0].length];
		gray = convertToGrayScale(img);
		return (getLMax(gray) - getLMin(gray)) / (double) getLmean(gray);
	}

	public static double calcK3(int[][][] img) {
		int[][] gray = new int[img.length][img[0].length];
		gray = convertToGrayScale(img);
		return (double) (getLMax(gray) - getLMin(gray))
				/ (double) (getLMax(gray) + getLMin(gray));
	}

	public static double calcK4(int[][][] img) {
		int[][] gray = new int[img[0].length][img[0].length];
		gray = convertToGrayScale(img);
		double pom = 0.0;
		double lmean = getLmean(gray);
		for (int i = 0; i < gray.length; ++i) {
			for (int j = 0; j < gray[0].length; ++j) {
				pom += Math.pow(gray[i][j] - lmean, 2.0);
			}
		}
		return (4*pom)/(L * L * gray[0].length * gray.length);
	}
	
	public static int[][][] toArray(BufferedImage im)
	{
		int[][][] img = new int[im.getWidth()][im.getHeight()][3];
		for (int i = 0; i < im.getWidth(); ++i) 
		{
			for (int j = 0; j < im.getHeight(); ++j) 
			{
				img[i][j][0]=(im.getRGB(i,j)>>16) & 0xFF;
				img[i][j][1]=(im.getRGB(i,j)>>8) & 0xFF;
				img[i][j][2]=(im.getRGB(i,j)) & 0xFF;
			}
    	}
		return img;
	}

}
